<?php
/** 
* 模型类文件
* 
* 留言的数据获取和视图标签的构建
* @author      sinalma  <sinalma@foxmail.com>
* @version     1.0 版本号
*/ 

namespace app\index\model;
use think\Model;
use think\Db;

/** 
 * Class Message
 * 留言模型类 
 *
 * @package app\index\model
 * @author      sinalma  <sinalma@foxmail.com>
 * @version     1.0 版本号
 */ 
class Message extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'sinblog_messages';
    private $htpURL = '';


    /**  
     * 添加留言 
     * 
     * @access public 
     * @param mixed $uid 用户uid
     * @param mixed $username 用户名
     * @param mixed $text 留言内容
     * @return bool（待返回)
     */  
    public function addMsg($uid,$username,$text){
        $text = htmlentities($text, ENT_QUOTES, 'UTF-8');
        $sql = "INSERT into sinblog_messages(uid,user_name,time,content) values('{$uid}','{$username}',unix_timestamp(now()),'{$text}')";
        $this->query($sql);
    }


    /**  
     * 添加留言的评论(顶级和非顶级),返回html,ajax请求是可调用此方法,以无刷新方式显示最新的留言评论
     * 
     * @access public 
     * @param mixed $data 评论信息的数组,如果是顶级评论,只需要(mid,uid,username,text),如果不是,另需(parent_id,cmt_name),mid在顶级评论代表留言的mid,非则表示评论的评论mid
     * @return html
     */ 
    public function addMsgCmt($data){
        $data['text'] = htmlentities($data['text'], ENT_QUOTES, 'UTF-8');
        $sql = '';
        if ($data['isTopCmt']){

            $sql = "INSERT into sinblog_messages(parent_id,uid,user_name,time,content) values('{$data['mid']}','{$data['uid']}','{$data['username']}',unix_timestamp(now()),'{$data['text']}')";
        }else{

            $sql = "INSERT into sinblog_messages(parent_id,uid,user_name,cmt_mid,cmt_name,time,content) values('{$data['parent_id']}','{$data['uid']}','{$data['username']}','{$data['mid']}','{$data['cmt_name']}',unix_timestamp(now()),'{$data['text']}')";
        }
        $res = $this->query($sql);
        // 获取当前新增的评论,调用方法获取此评论的信息
        $submsg = $this->query("SELECT * from sinblog_messages order by mid desc limit 1");
        return $this->getCmt($submsg[0]);
    }


    /**  
     * 获取留言数据(页)，返回html数据
     * 
     * @access public 
     * @param mixed $limitStr sql查询的限制,格式:limit 0,5
     * @param mixed $pageNum 每页显示的留言数
     * @return string 
     */  
    public function getMessages($limitStr,$pageNum){

        // 要先判断数据库表中有没有数据,如果没有,加了limit会报错
        $totalCount = $this->getCount();
        $limitStr = $totalCount >= $pageNum ? $limitStr : "";
        $sql = "SELECT * from sinblog_messages where parent_id=0 order by time desc ".$limitStr ;
        $res = $this->query($sql);
        $html = "";

        $page = input('param.page');
        $totalPage = ceil($totalCount/$pageNum);
        $prePage = $page <= 1 ? 1 : $page - 1;
        $nextPage = $page >= $totalPage ? $totalPage : $page + 1;

$html .= <<<eof
<div class="msg-title">
        <div class="page-count">留言(<span>{$totalCount}</span>)</div>
        <div class="msg-page-title">
            <a href='javascript:showmsgpage("{$this->htpURL}/index/Message/getMessages/page/{$prePage}")' class="msg-pre" id="msg-pre">上一页</a>
            <a href='javascript:showmsgpage("{$this->htpURL}/index/Message/getMessages/page/{$nextPage}")'  class="msg-next" id="msg-next">下一页</a>
        </div>
</div> 
<ul class="msg-ul">
eof;

        // 构建html
        for ($i=0; $i < count($res); $i++) { 
        $date = date('Y-m-d H:m:s',$res[$i]['time']);
        $uid = $res[$i]['uid'];
        $picUrl = $this->getProfilePic($uid);
$html .= <<<eof
    <li msgId="{$res[$i]['mid']}">
        <div class="msg-left">
            <a href="#"><img class="msg-avat-img" src="{$picUrl}"/></a>
            <a href="javascript:showCmtInput({$res[$i]['mid']})" class="msg-cmt-btn">回复</a>
        </div>
        <div class="msg-inner">
            <div class="msg-op"><a><i class="glyphicon glyphicon-triangle-bottom"></i></a></div>
            <p class="msg-name">{$res[$i]['user_name']}</p>
            <div class="msg-text">{$res[$i]['content']}</div>
            <p class="msg-time">{$date}</p>
            
        </div>
        <div class="msg-cmt">
            <textarea class="msg-cmt-input"></textarea>
            <p><a href="javascript:cmtSubmit({$res[$i]['mid']},1)" class="msg-cmt-sub-btn">提交</a></p>
        </div>
        <ul class="sub-msg">   
eof;
        $submsg = $this->query("SELECT * from sinblog_messages where parent_id='{$res[$i]['mid']} order by time desc'");
        // 获取子评论
        for ($j=0; $j < count($submsg); $j++) { 
            $html .= $this->getCmt($submsg[$j]);
        }

$html .= <<<eof
        </ul>
    </li>
eof;
        }
$html .= "</ul>";

        return $html;
    }


    /**  
     * 获取用户头像链接
     * 
     * @access public 
     * @param mixed $uid 用户id
     * @return string 
     */      
    public function getProfilePic($uid){
        $sql_n = "SELECT profile_pic from sinblog_user_list where uid='{$uid}'";
        // return $sql_n;
        $user = $this->query($sql_n);
        $picUrl = $user[0]['profile_pic'];
        return $picUrl;
    }


    /**  
     * 根据留言评论信息,构建html语句(ajax和非ajax都可调用)
     * 
     * @access public 
     * @param mixed $submsg 留言评论数据
     * @return string 
     */  
    public function getCmt($submsg){
        $date = date('Y-m-d H:m:s',$submsg['time']);   
        $name_prefix = $submsg['cmt_name']?"@".$submsg['cmt_name'].":":"";
        $picUrl = $this->getProfilePic($submsg['uid']);
$html = <<<eof
    <li msgId="{$submsg['mid']}">
        <div class="msg-left">
            <a href="#"><img class="msg-avat-img" src="{$picUrl}"/></a>
            <a href="javascript:showCmtInput({$submsg['mid']})" class="msg-cmt-btn">回复</a>
        </div>
        <div class="msg-inner">
            <div class="msg-op"><a><i class="glyphicon glyphicon-triangle-bottom"></i></a></div>
            <p class="msg-name">{$submsg['user_name']}</p>
            <div class="msg-text">{$name_prefix}{$submsg['content']}</div>
            <p class="msg-time">{$date}</p>
        </div>
        <div class="msg-cmt">
            <textarea class="msg-cmt-input"></textarea>
            <p><a href="javascript:cmtSubmit({$submsg['mid']},0)" class="msg-cmt-sub-btn">提交</a></p>
        </div>  
    </li>   
eof;
        return $html;
    }


    /**  
     * 获取总留言数 
     * 
     * @access public 
     * @return int 
     */  
    public function getCount(){
        $data = $this->query("SELECT count(*) as count from sinblog_messages where parent_id=0");
        return $data[0]["count"];
    }
    
}